import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Card,
  Table,
  Icon,
  Form,
  Row,
  Col,
  Button,
  DatePicker,
  Spin,
  Badge,
  message,
  Select,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Ellipsis from '@/components/Ellipsis';
import moment from 'moment';
import { startTime, endTime } from '@/utils/utils';
import styles from '../Common/TableList.less';
import AppSelect from '../Common/AppSelect';
import MobileQueryInput from '../Common/MobileQueryInput';
import { DictValue, DictSelect } from '../Common/Dict';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;

const sendResultDom = {
  success: <Badge status="success" text="成功" />,
  error: <Badge status="error" text="失败" />,
};

@connect(({ smsLog, loading }) => ({
  smsLog,
  loading: loading.effects['smsLog/fetch'],
}))
@Form.create()
class SmsLog extends PureComponent {
  state = {
    rangeTime: [],
  };

  columns = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (text, record, index) => index + 1,
    },
    {
      title: '应用ID',
      dataIndex: 'appId',
    },
    {
      title: '应用名称',
      dataIndex: 'appName',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },
    {
      title: '发送结果',
      dataIndex: 'sendResult',
      render: test => (test === '0' ? sendResultDom.success : sendResultDom.error),
    },
    {
      title: '状态',
      dataIndex: 'failReason',
      render: value => (
        <Ellipsis length={5} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    {
      title: '接收结果',
      dataIndex: 'receiveResult',
      render: value => <DictValue index="sms_receive_result" value={value} />,
    },
    {
      title: '接收详情',
      dataIndex: 'receiveDesc',
      render: value => (
        <Ellipsis length={5} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    {
      title: '发送时间',
      dataIndex: 'sendTime',
      render: value => moment(value).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '内容',
      dataIndex: 'content',
      render: value => (
        <Ellipsis length={3} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    {
      title: 'IP',
      dataIndex: 'requestIp',
      render: value => (
        <Ellipsis length={3} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    {
      title: '流水号',
      dataIndex: 'smsId',
      render: value => (
        <Ellipsis length={3} tooltip>
          {value}
        </Ellipsis>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'smsLog/reset' });
  }

  handleTableChange = pagination => {
    const { current, pageSize } = pagination;
    const { dispatch } = this.props;
    const params = {
      page: current - 1,
      size: pageSize,
    };
    dispatch({ type: 'smsLog/fetch', payload: params });
  };

  handleExport = () => {
    const {
      dispatch,
      smsLog: { query },
    } = this.props;
    dispatch({
      type: 'smsLog/batchExport',
      payload: query,
    }).then(() => {
      message.success('导出成功');
    });
  };

  handleSearch = query => {
    const { dispatch, form } = this.props;
    form.validateFields(err => {
      if (!err) {
        dispatch({
          type: 'smsLog/fetch',
          payload: { ...query, page: 0 },
        });
      }
    });
  };

  handleReset = () => {
    this.setState({ rangeTime: [] });
    const { dispatch } = this.props;
    dispatch({ type: 'smsLog/reset' });
  };

  renderForm = () => {
    const {
      smsLog: { exporting, query },
    } = this.props;
    const { rangeTime } = this.state;
    return (
      <Form layout="inline">
        <Row gutter={16}>
          <Col md={6}>
            <FormItem label="所属应用">
              <AppSelect
                allowClear
                value={query.appId}
                onChange={appId => this.handleSearch({ appId })}
              />
            </FormItem>
          </Col>
          <Col md={6}>
            <FormItem label="手机号">
              <MobileQueryInput
                allowClear
                value={query.mobile}
                onChange={mobile => this.handleSearch({ mobile })}
              />
            </FormItem>
          </Col>
          <Col md={6}>
            <FormItem label="发送结果">
              <Select
                allowClear
                placeholder="请选择"
                value={query.sendResult}
                onChange={sendResult => this.handleSearch({ sendResult })}
              >
                <Select.Option key="0" value="0">
                  {sendResultDom.success}
                </Select.Option>
                <Select.Option key="1" value="1">
                  {sendResultDom.error}
                </Select.Option>
              </Select>
            </FormItem>
          </Col>
          <Col md={6}>
            <FormItem label="接收结果">
              <DictSelect
                allowClear
                index="sms_receive_result"
                value={query.receiveResult}
                onChange={receiveResult => this.handleSearch({ receiveResult })}
              />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col md={12}>
            <FormItem label="登录时间">
              <RangePicker
                allowClear
                value={rangeTime}
                showTime={{
                  format: 'HH:mm',
                  defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')],
                }}
                format="YYYY-MM-DD HH:mm"
                placeholder={['开始时间', '结束时间']}
                onChange={dates => {
                  this.setState({ rangeTime: dates });
                  if (!dates.length) this.handleSearch({ startSendTime: null, endSendTime: null });
                }}
                onOk={() => {
                  const startSendTime = rangeTime[0] ? startTime(rangeTime[0]) : null;
                  const endSendTime = rangeTime[1] ? endTime(rangeTime[1]) : null;
                  this.handleSearch({ startSendTime, endSendTime });
                }}
              />
            </FormItem>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col md={8}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.handleSearch({})}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                重置
              </Button>
              {exporting ? (
                <a href="#" style={{ marginLeft: 10 }}>
                  <Spin size="small" /> 批量导出中...
                </a>
              ) : (
                <a onClick={this.handleExport} style={{ marginLeft: 10 }}>
                  <Icon type="export" /> 批量导出
                </a>
              )}
            </span>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const {
      smsLog: { list },
      loading,
    } = this.props;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: list.pagination.total, // 总条数
      showTotal: () => `共${list.pagination.total}条`, // 展示总条数
      ...list.pagination,
    };
    return (
      <PageHeaderWrapper title="短信发送列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <Table
              size="middle"
              rowKey="id"
              columns={this.columns}
              loading={loading}
              dataSource={list.data}
              pagination={paginationProps}
              onChange={this.handleTableChange}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default SmsLog;
